<?php
class helper_baseUrl extends system_view_helper_abstract {
	
	protected $_baseUrl;	
	public function baseUrl($file = null) {
		$baseUrl = $this->getBaseUrl();
		if(null !== $file) {
			if(preg_match('/^[^\\\\\/]+\:\/\/(.*)$/is', $file)) {
				return $file;
			}
			$file = '/' . ltrim($file, '/\\');
		}		
		return $baseUrl . $file;
	}
	
	public function setBaseUrl($base) {
		$this->_baseUrl = rtrim($base, '/\\');
		return $this;
	}
	
	public function getBaseUrl() {
		if($this->_baseUrl === null) {
			$baseUrl = system_controller_front::getInstance()->getBaseUrl();
			$baseUrl = $this->_removeScriptName($baseUrl);			
			$this->setBaseUrl($baseUrl);
		}		
		return $this->_baseUrl;
	}
	
	protected function _removeScriptName($url) {
		if(!isset($_SERVER['SCRIPT_NAME'])) {
			return $url;
		}		
		if(($pos = strripos($url, basename($_SERVER['SCRIPT_NAME']))) !== false) {
			$url = substr($url, 0, $pos);
		}		
		return $url;
	}
}